<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="药膳名称">
          <el-input v-model="queryParams.name" placeholder="请输入药膳名称" clearable />
        </el-form-item>
        <el-form-item label="功效">
          <el-select v-model="queryParams.effect" placeholder="请选择功效" clearable>
            <el-option label="补气" value="补气" />
            <el-option label="养血" value="养血" />
            <el-option label="温阳" value="温阳" />
            <el-option label="利水渗湿" value="利水渗湿" />
            <el-option label="收敛" value="收敛" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="queryParams.category" placeholder="请选择分类" clearable>
            <el-option label="汤" value="汤" />
            <el-option label="酒" value="酒" />
            <el-option label="粥" value="粥" />
            <el-option label="饼" value="饼" />
            <el-option label="面" value="面" />
            <el-option label="茶" value="茶" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="action-container">
      <el-button type="primary" @click="handleAdd">新增药膳</el-button>
      <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="recipeList"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="药膳名称" prop="name" min-width="150" show-overflow-tooltip />
      <el-table-column label="分类" prop="category" width="100" align="center" />
      <el-table-column label="功效" prop="effects" min-width="150">
        <template #default="{ row }">
          <el-tag v-for="effect in row.effects" :key="effect" style="margin-right: 5px">{{ effect }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="主要食材" prop="ingredients" min-width="200" show-overflow-tooltip />
      <el-table-column label="状态" prop="status" width="100" align="center">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="160" align="center" />
      <el-table-column label="操作" width="180" align="center">
        <template #default="{ row }">
          <el-button type="text" @click="handleView(row)">查看</el-button>
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" style="color: #f56c6c" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑药膳对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="700px"
      destroy-on-close
      append-to-body
    >
      <el-form
        ref="recipeFormRef"
        :model="recipeForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="药膳名称" prop="name">
          <el-input v-model="recipeForm.name" placeholder="请输入药膳名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="recipeForm.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="汤" value="汤" />
            <el-option label="酒" value="酒" />
            <el-option label="粥" value="粥" />
            <el-option label="饼" value="饼" />
            <el-option label="面" value="面" />
            <el-option label="茶" value="茶" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="功效" prop="effects">
          <el-select
            v-model="recipeForm.effects"
            multiple
            placeholder="请选择功效"
            style="width: 100%"
          >
            <el-option label="补气" value="补气" />
            <el-option label="养血" value="养血" />
            <el-option label="温阳" value="温阳" />
            <el-option label="利水渗湿" value="利水渗湿" />
            <el-option label="收敛" value="收敛" />
          </el-select>
        </el-form-item>
        <el-form-item label="食材组成">
          <div v-for="(item, index) in recipeForm.ingredientList" :key="index" style="display: flex; margin-bottom: 10px">
            <el-select
              v-model="item.ingredient"
              placeholder="选择食材"
              style="width: 180px; margin-right: 10px"
              filterable
              clearable
            >
              <el-option
                v-for="option in ingredientOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
            <el-input-number
              v-model="item.amount"
              :min="1"
              :max="1000"
              placeholder="用量"
              style="width: 120px; margin-right: 10px"
            />
            <el-select
              v-model="item.unit"
              placeholder="单位"
              style="width: 80px; margin-right: 10px"
            >
              <el-option label="克" value="克" />
              <el-option label="毫升" value="毫升" />
              <el-option label="个" value="个" />
              <el-option label="片" value="片" />
              <el-option label="根" value="根" />
            </el-select>
            <el-button type="danger" icon="Delete" @click="removeIngredient(index)" />
          </div>
          <el-button type="primary" icon="Plus" @click="addIngredient">添加食材</el-button>
        </el-form-item>
        <el-form-item label="制作方法" prop="method">
          <el-input
            v-model="recipeForm.method"
            type="textarea"
            :rows="4"
            placeholder="请输入制作方法"
          />
        </el-form-item>
        <el-form-item label="功效说明" prop="description">
          <el-input
            v-model="recipeForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入功效说明"
          />
        </el-form-item>
        <el-form-item label="图片上传">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleUploadChange"
            :on-remove="handleUploadRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="recipeForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看药膳详情对话框 -->
    <el-dialog
      v-model="viewDialog.visible"
      title="药膳详情"
      width="700px"
      append-to-body
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="药膳名称">{{ recipeDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ recipeDetail.category }}</el-descriptions-item>
        <el-descriptions-item label="功效">
          <el-tag
            v-for="effect in recipeDetail.effects"
            :key="effect"
            style="margin-right: 5px"
          >
            {{ effect }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="食材组成">
          <div v-for="(item, index) in recipeDetail.ingredientList" :key="index">
            {{ item.ingredient }} {{ item.amount }}{{ item.unit }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="制作方法">{{ recipeDetail.method }}</el-descriptions-item>
        <el-descriptions-item label="功效说明">{{ recipeDetail.description }}</el-descriptions-item>
        <el-descriptions-item label="图片">
          <div class="image-preview">
            <el-image
              v-for="(url, index) in recipeDetail.images"
              :key="index"
              :src="url"
              :preview-src-list="recipeDetail.images"
              fit="cover"
              style="width: 100px; height: 100px; margin-right: 10px"
            />
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="recipeDetail.status === 1 ? 'success' : 'danger'">
            {{ recipeDetail.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ recipeDetail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ recipeDetail.updateTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getRecipeList, getRecipeDetail, addRecipe, updateRecipe, deleteRecipe, updateRecipeStatus } from '@/api/knowledge'

const loading = ref(false)
const recipeList = ref([])
const total = ref(0)
const selectedIds = ref([])
const recipeFormRef = ref()
const fileList = ref([])

// 药材选项
const ingredientOptions = ref([
  { label: '黄芪', value: '黄芪' },
  { label: '当归', value: '当归' },
  { label: '枸杞', value: '枸杞' },
  { label: '红枣', value: '红枣' },
  { label: '白术', value: '白术' },
  { label: '茯苓', value: '茯苓' },
  { label: '党参', value: '党参' },
  { label: '白芍', value: '白芍' },
  { label: '甘草', value: '甘草' },
  { label: '山药', value: '山药' }
])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  category: '',
  effect: ''
})

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入药膳名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  effects: [{ required: true, message: '请选择功效', trigger: 'change' }],
  method: [{ required: true, message: '请输入制作方法', trigger: 'blur' }],
  description: [{ required: true, message: '请输入功效说明', trigger: 'blur' }]
}

// 对话框状态
const dialog = reactive({
  visible: false,
  title: '',
  type: ''
})

// 查看详情对话框状态
const viewDialog = reactive({
  visible: false
})

// 药膳表单对象
const recipeForm = reactive({
  id: undefined,
  name: '',
  category: '',
  effects: [],
  ingredientList: [{ ingredient: '', amount: 10, unit: '克' }],
  method: '',
  description: '',
  images: [],
  status: 1
})

// 药膳详情对象
const recipeDetail = reactive({
  id: '',
  name: '',
  category: '',
  effects: [],
  ingredientList: [],
  method: '',
  description: '',
  images: [],
  status: 0,
  createTime: '',
  updateTime: ''
})

// 获取药膳列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getRecipeList(queryParams)
    recipeList.value = res.data.rows
    total.value = res.data.total
  } catch (error) {
    console.error('获取药膳列表失败', error)
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  getList()
})

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.name = ''
  queryParams.category = ''
  queryParams.effect = ''
  handleQuery()
}

// 表格选择行变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 每页数量变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getList()
}

// 添加药膳
const handleAdd = () => {
  resetForm()
  dialog.title = '添加药膳'
  dialog.type = 'add'
  dialog.visible = true
}

// 编辑药膳
const handleEdit = async (row) => {
  resetForm()
  dialog.title = '编辑药膳'
  dialog.type = 'edit'
  dialog.visible = true
  
  const res = await getRecipeDetail(row.id)
  Object.assign(recipeForm, res.data)
  
  // 处理图片列表
  fileList.value = recipeForm.images.map((url, index) => ({
    name: `图片${index + 1}`,
    url
  }))
}

// 查看药膳详情
const handleView = async (row) => {
  const res = await getRecipeDetail(row.id)
  Object.assign(recipeDetail, res.data)
  viewDialog.visible = true
}

// 删除药膳
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除药膳 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    // 添加调试日志
    console.log('删除药膳，ID:', row.id)
    deleteRecipe(row.id).then(response => {
      console.log('删除成功，响应:', response)
      ElMessage.success('删除成功')
      getList()
    }).catch(error => {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }).finally(() => {
      loading.value = false
    })
  }).catch(() => {
    // 用户取消删除操作
  })
}

// 批量删除药膳
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条数据吗？`, '警告', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    await deleteRecipe(selectedIds.value.join(','))
    ElMessage.success('批量删除成功')
    getList()
  }).catch(() => {})
}

// 修改药膳状态
const handleStatusChange = (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '停用'

  ElMessageBox.confirm(`确定${statusText}药膳 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    console.log('更新药膳状态，ID:', row.id, '新状态:', newStatus)
    updateRecipeStatus(row.id, newStatus).then(response => {
      console.log('状态更新成功，响应:', response)
      ElMessage.success(`${statusText}成功`)
      getList()
    }).catch(error => {
      console.error('状态更新失败:', error)
      ElMessage.error(`${statusText}失败`)
    }).finally(() => {
      loading.value = false
    })
  }).catch(() => {
    // 用户取消操作
  })
}

// 重置表单
const resetForm = () => {
  recipeForm.id = undefined
  recipeForm.name = ''
  recipeForm.category = ''
  recipeForm.effects = []
  recipeForm.ingredientList = [{ ingredient: '', amount: 10, unit: '克' }]
  recipeForm.method = ''
  recipeForm.description = ''
  recipeForm.images = []
  recipeForm.status = 1
  fileList.value = []
}

// 添加食材
const addIngredient = () => {
  recipeForm.ingredientList.push({ ingredient: '', amount: 10, unit: '克' })
}

// 移除食材
const removeIngredient = (index) => {
  recipeForm.ingredientList.splice(index, 1)
}

// 处理图片上传变化
const handleUploadChange = (file) => {
  // 实际应用中需要调用上传API
  // 这里模拟上传成功后的行为
  const reader = new FileReader()
  reader.onload = (e) => {
    if (!fileList.value.some(item => item.uid === file.uid)) {
      fileList.value.push(file)
    }
  }
  reader.readAsDataURL(file.raw)
}

// 处理图片移除
const handleUploadRemove = (file) => {
  fileList.value = fileList.value.filter(item => item.uid !== file.uid)
}

// 提交表单
const submitForm = () => {
  recipeFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      
      // 构建提交数据
      const submitData = {
        ...recipeForm,
        // 处理成分列表格式
        ingredientList: recipeForm.ingredientList.map(item => ({
          ingredient: item.ingredient,
          amount: parseFloat(item.amount),
          unit: item.unit
        }))
      }
      
      console.log('提交数据:', submitData)
      
      if (dialog.type === 'edit') {
        updateRecipe(submitData).then(response => {
          console.log('更新成功，响应:', response)
          ElMessage.success('更新成功')
          dialog.visible = false
          getList()
        }).catch(error => {
          console.error('更新失败:', error)
          ElMessage.error('更新失败')
        }).finally(() => {
          loading.value = false
        })
      } else {
        addRecipe(submitData).then(response => {
          console.log('添加成功，响应:', response)
          ElMessage.success('添加成功')
          dialog.visible = false
          getList()
        }).catch(error => {
          console.error('添加失败:', error)
          ElMessage.error('添加失败')
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .filter-container {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
  }
  
  .action-container {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  .image-preview {
    display: flex;
    flex-wrap: wrap;
  }
}
</style> 